package druid.dao;

import druid.entity.Tip;
import druid.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class TipDao {
    /**
     * 在帖子中添加一条记录
     */

    public boolean add(Tip tip){
        Connection conn = null;
        PreparedStatement pstam = null;
        try{
            conn = JDBCUtils.getConnection();

            Integer id = tip.getId();
            String name = tip.getName();
            Integer good = tip.getGood();
            Integer bad = tip.getBad();
            Date time = tip.getDate();
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time1 = f.format(time);
            String title = tip.getTitle();
            String sql = "insert into tip values (?,?,?,?,?,2,?)";
            pstam= conn.prepareStatement(sql);
            pstam.setInt(1,id);
            pstam.setString(2,name);
            pstam.setInt(3,good);
            pstam.setInt(4,bad);
            pstam.setString(5,time1);
            pstam.setString(6,title);

            int result = pstam.executeUpdate();

            if (result>0){
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(null,conn,pstam);
        }
        return false;
    }

    public List<Tip> select(String info){
        Connection conn = null;
        PreparedStatement pstam = null;
        ResultSet resultSet=null;
        try{
            conn = JDBCUtils.getConnection();

            String sql = "select * from tip where tip_name LIKE ?";
            pstam = conn.prepareStatement(sql);
            pstam.setString(1,"%"+info+"%");
            resultSet = pstam.executeQuery();

            List<Tip> list = new ArrayList<>();
            while(resultSet.next()){
                Tip tip = new Tip();
                tip.setId(resultSet.getInt(1));
                tip.setName(resultSet.getString(2));
                tip.setGood(resultSet.getInt(3));
                tip.setBad(resultSet.getInt(4));
                tip.setDate(resultSet.getDate(5));
                tip.setTitle(resultSet.getString(7));
                list.add(tip);

            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(resultSet,conn,pstam);
        }
        return null;
    }
}
